package es.xpt.ysf.commons.business.view;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import es.xpt.ysf.YSFException;
import es.xpt.ysf.commons.business.model.Currency;
import es.xpt.ysf.commons.business.model.CurrencyExchange;
import es.xpt.ysf.commons.business.model.Period;
import es.xpt.ysf.logging.LogManager;
import es.xpt.ysf.model.Item;
import es.xpt.ysf.utils.TimeUtils;
import es.xpt.ysf.view.Controller;

@SuppressWarnings("serial")
public class CurrencyExchangeController extends Controller // NO_UCD 
{ 	
	private CurrencyExchange currencyExchange = new CurrencyExchange();
    private List<CurrencyExchangeModelView> currencyExchangeList;
    private Date originalInitDate;
    private CurrencyExchangeHelper helper = new CurrencyExchangeHelper();
	
	public CurrencyExchangeController() 
	{
		super();
		setMessageBundle("es.xpt.ysf.commons.business.Messages");
	}
	
	public String editMode() 
	{
		setCurrencyExchange(parse((CurrencyExchangeModelView)helper.getHtmlDataTable().getRowData(),currencyExchange.getInitDate()));
		setOriginalInitDate(currencyExchange.getInitDate());
		helper.setEditMode(true);
		
		return "success";
	}
	
    public String cancel() 
    {
		helper.setEditMode(false);
		setCurrencyExchange(new CurrencyExchange());
		setCurrencyExchangeList(null);

        return "success";
    }
	
    public String save() 
    {
    	try 
    	{
    		validateCurrencyExchange(currencyExchange,originalInitDate);
    		if(originalInitDate==null)
    		{
				new BusinessDelegate(getUserBean()).insertExchange(currencyExchange);
				super.setInfoMessage("commons.currencyExchange.create");
    		}
    		else
    		{
    			new BusinessDelegate(getUserBean()).updateExchanges(currencyExchange,originalInitDate);
    			super.setInfoMessage("commons.currencyExchange.update");
    			setOriginalInitDate(null);
        		helper.setEditMode(false);
    		}
			setCurrencyExchange(new CurrencyExchange());
			setCurrencyExchangeList(null);
		} 
    	catch (YSFException e) 
    	{
			super.setErrorMessage(e);
			LogManager.getLog(getClass()).error(e.getMessage(), e);
			return "failure";
		}
    	
        return "success";
    }
    
    public String delete() 
	{
    	try 
    	{
    		setCurrencyExchange(parse((CurrencyExchangeModelView)helper.getHtmlDataTable().getRowData(),currencyExchange.getInitDate()));			
			new BusinessDelegate(getUserBean()).deleteExchanges(currencyExchange);
			super.setInfoMessage("commons.currencyExchange.delete");
			setCurrencyExchange(new CurrencyExchange());
			setCurrencyExchangeList(null);
    	}
    	catch (YSFException e) 
    	{
    		super.setErrorMessage(e);
    		LogManager.getLog(getClass()).error(e.getMessage(), e);
			return "failure";
    	}

    	return "success";
	}    
    
    public String deleteList ()  
	{
    	if (!helper.getSelectedExchangeList().isEmpty())
    	{
    		List<String> listMessages;
    		try 
    		{
    			List<CurrencyExchange> deleteCurrencyExchangeList = new ArrayList<CurrencyExchange>(0);
				for (String selectedExchange : helper.getSelectedExchangeList()) 
				{
					CurrencyExchange currentCurrencyExchange = new CurrencyExchange();
					currentCurrencyExchange.setSource(selectedExchange.substring(0, 3));
					currentCurrencyExchange.setTarget(selectedExchange.substring(3, 6));
					deleteCurrencyExchangeList.add(currentCurrencyExchange);
				}	
				
				listMessages = new BusinessDelegate(getUserBean()).deleteBatchCurrencyExchanges(deleteCurrencyExchangeList);
				if (listMessages==null || listMessages.isEmpty())
				{
					super.setInfoMessage("commons.currencyExchange.delete");
				}
				else if( listMessages.size()>0) 
				{
					for(int i=0;listMessages.size()>=(i+1);i=i+2)
					{
						CurrencyExchangeModelView currexTemp = new CurrencyExchangeModelView();
			 			int j=currencyExchangeList.indexOf(currexTemp);
			 			super.setErrorMessage(listMessages.get(i),currencyExchangeList.get(j).getSource()+"-"+
	 					currencyExchangeList.get(j).getTarget()+"-"+currencyExchangeList.get(j).getExchangeInPeriod());
					}
				}
    		} 
    		catch (YSFException e) 
    		{
    			super.setErrorMessage(e);							
    			LogManager.getLog(getClass()).error(e.getMessage(), e);
    		}
    	}
    	setCurrencyExchangeList(null);

		return "success";
	}
    
	/* *****************
	 * PRIVATE METHODS *
	 * *************** */
	
    private CurrencyExchange parse(CurrencyExchangeModelView param, Date initDate)
	{
    	if(param==null)
    		throw new NullPointerException("currencyExchangeModelView");
    	if(param.getExchangeInPeriod()==null || param.getExchangeInPeriod().isEmpty())
    		throw new NullPointerException("exchangeInPeriod");
    	if(initDate==null)
    		throw new NullPointerException("initDate");
    	
		CurrencyExchange result = new CurrencyExchange();
		result.setSource(param.getSource());
		result.setTarget(param.getTarget());
		Iterator<Period> periodIt = param.getExchangeInPeriod().keySet().iterator();
		while(periodIt.hasNext())
		{
			Period currentPeriod = periodIt.next();
			if(TimeUtils.truncateToDate(currentPeriod.getInitDate()).equals(TimeUtils.truncateToDate(initDate)))
			{
				result.setInitDate(currentPeriod.getInitDate());
				result.setEndDate(currentPeriod.getEndDate());
				result.setExchange(param.getExchangeInPeriod().get(currentPeriod));
				break;
			}
		}
		
		return result;
	}
	 
    private List<CurrencyExchangeModelView> parse(List<CurrencyExchange> param)
    {
    	List<CurrencyExchangeModelView> result = new ArrayList<CurrencyExchangeModelView>(0);
		for (CurrencyExchange currencyExchange : param) 
		{		
			CurrencyExchangeModelView currencyResult = null;
			for (CurrencyExchangeModelView currencyExchangeModelView : result) 
			{
				if(currencyExchangeModelView.getSource().equals(currencyExchange.getSource()) && currencyExchangeModelView.getTarget().equals(currencyExchange.getTarget()))
				{
					currencyResult = currencyExchangeModelView;
					break;
				}
			}
			
			if(currencyResult!=null)
				currencyResult.getExchangeInPeriod().put(new Period(currencyExchange.getInitDate(), currencyExchange.getEndDate()), currencyExchange.getExchange());
			else
			{
				currencyResult = new CurrencyExchangeModelView(currencyExchange.getSource(),currencyExchange.getTarget());
				currencyResult.getExchangeInPeriod().put(new Period(currencyExchange.getInitDate(), currencyExchange.getEndDate()), currencyExchange.getExchange());
				result.add(currencyResult);
			}
		}
		 
		return result;
	}
	
    private void validateCurrencyExchange(CurrencyExchange param, Date originalInitDate) throws YSFException
	{
    	Date initDate = TimeUtils.truncateToDate(param.getInitDate());
    	Date endDate = TimeUtils.truncateToDate(param.getEndDate());
    	
		if(initDate.after(endDate))
			throw new YSFException("commons.currencyExchange.datesValidation.initDateNotValid");
		
		List<CurrencyExchange> currencyExchangeList = new BusinessDelegate(getUserBean()).
				getExchangesByCurrencies(new Currency(new Item(param.getSource(), null)),new Currency(new Item(param.getTarget(), null)));
		for (CurrencyExchange currencyExchange : currencyExchangeList)
		{
	    	Date currentInitDate = TimeUtils.truncateToDate(currencyExchange.getInitDate());
	    	Date currentEndDate = TimeUtils.truncateToDate(currencyExchange.getEndDate());
	    	
			if(originalInitDate!=null && currentInitDate.equals(TimeUtils.truncateToDate(originalInitDate)))
				continue;
			if(!initDate.before(currentInitDate) && !initDate.after(currentEndDate))
				throw new YSFException("commons.currencyExchange.datesValidation.initDateOutPeriod");
			if(!endDate.before(currentInitDate) && !endDate.after(currentEndDate))
				throw new YSFException("commons.currencyExchange.datesValidation.endDateOutPeriod");
			if(!initDate.after(currentInitDate) && !endDate.before(currentEndDate))
				throw new YSFException("commons.currencyExchange.datesValidation.periodContains");
		}
	}
	
	/* ********************
	 * GETTERS && SETTERS *
	 * ****************** */
	
	public CurrencyExchange getCurrencyExchange() { return currencyExchange; }
	public void setCurrencyExchange(CurrencyExchange currencyExchange) { this.currencyExchange = currencyExchange; }
	
	public List<CurrencyExchangeModelView> getCurrencyExchangeList() 
	{	
		try 
		{
			if(currencyExchangeList == null)
				currencyExchangeList = parse(new BusinessDelegate(getUserBean()).getAllExchanges());
		} 
		catch (YSFException e) 
		{
			LogManager.getLog(getClass()).error(e.getMessage(), e);
		}
		return currencyExchangeList;
	}
	public void setCurrencyExchangeList(List<CurrencyExchangeModelView> currencyExchangeList) { this.currencyExchangeList = currencyExchangeList; }
	
	public Date getOriginalInitDate() { return originalInitDate; }
	public void setOriginalInitDate(Date originalInitDate) { this.originalInitDate = originalInitDate; }

	public CurrencyExchangeHelper getHelper() { return helper; }
	public void setHelper(CurrencyExchangeHelper helper) { this.helper = helper; }
}